﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MathofLerp : MonoBehaviour {

	public Vector3[] VecArray;
	// Use this for initialization
	void Start () {

		//调用 传参数  时间 、速度 
		getDistance (3, 1);
	}

	void getDistance(float t, float v){


		//初始化坐标点 模拟数据

		VecArray = new Vector3[20] {
			new Vector3 (-1f, 0.8f, -0.01f),
			new Vector3 (-2f, 0.4f, -0.01f),
			new Vector3 (-3f, -3f, -0.01f),
			new Vector3 (-4f, -0.4f, -0.01f),
			new Vector3 (-5f, -0.8f, -0.01f),
			new Vector3 (-3f, 0.8f, -0.01f),
			new Vector3 (2.5f, 0.4f, -0.01f),
			new Vector3 (2.5f, 0f, -0.01f),
			new Vector3 (2.5f, -0.4f, -0.01f),
			new Vector3 (2.5f, -0.8f, -0.01f),
			new Vector3 (-1f, 0.8f, -1f),
			new Vector3 (-2f, 0.4f, -2f),
			new Vector3 (-3f, -3f, -3f),
			new Vector3 (-4f, -0.4f, -4f),
			new Vector3 (-5f, -0.8f, -5),
			new Vector3 (-3f, 0.8f, -3),
			new Vector3 (2.5f, 0.4f, 1f),
			new Vector3 (2.5f, 0f, 2f),
			new Vector3 (2.5f, -0.4f, 3f),
			new Vector3 (2.5f, -0.8f, 4f)

		};


		//时间 为3秒时的位置
//		float t = 3;

		//速度 为常数1 

//		float v = 1;

		//t 时间后运动的路程   
		float s = v *t ;

		//两个空间向量间的距离
		float l = 0;

		//d  临时变量 存储数据
		float d = 0 ;

		// n 存储下标
		int n = 0;

		//lerp 函数比例 t1

		float t1;
		//计算t 时间后物体的位置


		for (int i = 0; i < 20 ; i ++){

			Debug.Log(VecArray[i]);
			//相邻两点距离相加
			Vector3 vecA = VecArray[i];
			Vector3 vecB = VecArray[i+1];

			d = d + Mathf.Abs (Mathf.Sqrt (Mathf.Pow ((vecB.x - vecA.x),2) + Mathf.Pow ((vecB.y - vecA.y),2)));

			if (d >= s) {

				n = i;
				//目标所在相邻两点间的距离
				l = Mathf.Abs (Mathf.Sqrt (Mathf.Pow ((vecB.x - vecA.x),2) + Mathf.Pow ((vecB.y - vecA.y),2)));

				//比例 t1 
				t1 = (s - d + l) / l;

				transform.position = Vector3.Lerp (VecArray [n], VecArray [n + 1], t1);

				Debug.Log ("结果是： ----------" + transform.position);



				break;
			}

			Debug.Log (n);


		}

	
	
	}

}
